import strHtml from "./ProductDetailsPage.html";
import { DomUtils } from "../../utils/DomUtils";
import { productService } from "../../services/productService";

export class ProductDetailsPage {
  constructor() {
    this.dom = null;
    this.product = null;
  }

  async render() {
    this.dom = DomUtils.convertToDom(strHtml);
    const product = JSON.parse(localStorage.getItem("selectedProduct") || "{}");

    if (!product.productId) {
      this.dom.innerHTML = '<div class="alert alert-danger">商品不存在</div>';
      return this.dom;
    }

    try {
      // 从后端获取最新商品信息
      const response = await productService.getById(product.productId);
      this.product = response;

      // 检查商品状态
      if (!this.product || this.product.status !== "上架") {
        this.dom.innerHTML =
          '<div class="alert alert-warning">该商品已下架</div>';
        return this.dom;
      }

      // 更新点击次数
      await this._incrementClickCount();

      // 渲染商品详情
      this._renderProductDetails(this.product);
      this._bindEvents();

      return this.dom;
    } catch (error) {
      console.error("加载商品详情失败:", error);
      this.dom.innerHTML =
        '<div class="alert alert-danger">加载商品详情失败</div>';
      return this.dom;
    }
  }

  async _incrementClickCount() {
    try {
      await productService.update(this.product.productId, {
        ...this.product,
        clickCount: (this.product.clickCount || 0) + 1,
      });
    } catch (error) {
      console.error("更新点击次数失败:", error);
    }
  }

  _renderProductDetails(product) {
    try {
      // 更新商品图片
      const productImage = this.dom.querySelector("#product-image");
      if (productImage) {
        productImage.src = product.productImageUrl || "";
        productImage.alt = product.productName || "商品图片";
      }

      // 更新商品基本信息
      const nameElement = this.dom.querySelector("#product-name");
      if (nameElement) {
        nameElement.innerText = product.productName || "未命名商品";
      }

      const priceElement = this.dom.querySelector("#product-price");
      if (priceElement) {
        priceElement.innerText = (product.productPrice || 0).toFixed(2);
      }

      // 更新生产溯源信息
      const originElement = this.dom.querySelector("#product-origin");
      if (originElement) {
        originElement.innerText = product.productionPlace || "未知生产地";
      }

      const cycleElement = this.dom.querySelector("#product-cycle");
      if (cycleElement) {
        cycleElement.innerText = product.productionPeriod || "未知生长周期";
      }

      const dateElement = this.dom.querySelector("#product-manufacture-date");
      if (dateElement) {
        dateElement.innerText = product.productionDate || "未知生产日期";
      }

      // 更新商品分类
      const categoryElement = this.dom.querySelector("#product-category");
      if (categoryElement) {
        let categoryName = product.category || "未知分类";
        if (categoryName === "fruit") categoryName = "水果";
        if (categoryName === "vegetable") categoryName = "蔬菜";
        categoryElement.innerText = categoryName;
      }

      // 更新库存信息
      const stockElement = this.dom.querySelector("#product-stock");
      if (stockElement) {
        stockElement.innerText =
          product.stock > 0 ? `库存: ${product.stock}` : "已售罄";
        stockElement.className = `badge ${
          product.stock > 0 ? "bg-success" : "bg-danger"
        }`;
      }

      // 更新点击次数
      const clickCountElement = this.dom.querySelector("#product-click-count");
      if (clickCountElement) {
        clickCountElement.innerText = `${product.clickCount || 0}`;
      }

      // 更新按钮状态
      const addToCartBtn = this.dom.querySelector(".btn-success");
      const buyNowBtn = this.dom.querySelector("#btn-buy-now");

      if (addToCartBtn && buyNowBtn) {
        const isOutOfStock = product.stock <= 0;
        addToCartBtn.disabled = isOutOfStock;
        buyNowBtn.disabled = isOutOfStock;

        // 更新按钮提示文本
        if (isOutOfStock) {
          addToCartBtn.title = "商品已售罄";
          buyNowBtn.title = "商品已售罄";
        } else {
          addToCartBtn.title = "加入购物车";
          buyNowBtn.title = "立即购买";
        }
      }
    } catch (error) {
      console.error("渲染商品详情时出错:", error);
    }
  }

  _bindEvents() {
    try {
      // 加入购物车按钮事件
      const addToCartBtn = this.dom.querySelector(".btn-success");
      if (addToCartBtn) {
        addToCartBtn.addEventListener("click", () => {
          if (!this.product) {
            alert("商品信息不存在！");
            return;
          }

          const cart = JSON.parse(localStorage.getItem("cart") || "[]");
          const existing = cart.find(
            (p) => p.productId === this.product.productId
          );

          if (existing) {
            if (existing.quantity < this.product.stock) {
              existing.quantity += 1;
            } else {
              alert("已达库存上限，无法继续添加！");
              return;
            }
          } else {
            if (this.product.stock > 0) {
              cart.push({ ...this.product, quantity: 1 });
            } else {
              alert("该商品已售罄，无法添加！");
              return;
            }
          }

          localStorage.setItem("cart", JSON.stringify(cart));
          alert("已添加到购物车！");
        });
      }

      // 立即购买按钮事件
      const buyNowBtn = this.dom.querySelector("#btn-buy-now");
      if (buyNowBtn) {
        buyNowBtn.addEventListener("click", () => {
          if (!this.product) {
            alert("商品信息不存在！");
            return;
          }

          if (this.product.stock <= 0) {
            alert("该商品已售罄！");
            return;
          }

          const maxQty = this.product.stock;
          let qty = prompt(`请输入购买数量（1-${maxQty}）：`, "1");

          if (qty === null) return; // 用户取消

          qty = parseInt(qty);
          if (isNaN(qty) || qty < 1) {
            alert("请输入有效的数量！");
            return;
          }

          if (qty > maxQty) {
            alert("超出库存上限！");
            return;
          }

          // 存储立即购买商品信息
          localStorage.setItem(
            "buyNowProduct",
            JSON.stringify({ ...this.product, quantity: qty })
          );

          location.hash = "#/check-out";
        });
      }
    } catch (error) {
      console.error("绑定事件时出错:", error);
    }
  }
}
